<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2023/3/1
 * Time: 10:41
 */

namespace app\middleware;


use think\Response;

class Login
{
    private $controller = ['Login','Email'];//跳过验证的控制器
    private $action = ['test','index'];//跳过验证的方法
    private $controller_action = [];
    /**
     * ApiAuth鉴权
     * @param \think\facade\Request $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     */
    public function handle($request, \Closure $next): Response {
        if (strtoupper($request->method()) == "OPTIONS")
            return json(['code' => 200, 'msg'  => '', 'data' => []],200);
        $ApiAuth = $request->header('Api-Auth', '');
        $controller = str_replace('sys.','',\think\facade\Request::controller());
        $action = \think\facade\Request::action();
        if(in_array($action,$this->action)) return $next($request);
        if(in_array($controller,$this->controller)) return $next($request);
        if(in_array($controller.'/'.$action,$this->controller_action))return $next($request);
        if (!empty($ApiAuth)) {
            $userInfo = cache($ApiAuth);
            $userInfo = json_decode($userInfo);
            if (empty($userInfo)) return json(['code' => 401, 'msg'  => 'ApiAuth不匹配', 'data' => []],200);
            global $user;
            $user = \app\model\Admin::where('id',$userInfo->id)->find();
            if ($user->token != $ApiAuth)
                return json(['code' => 401, 'msg'  => '检测到账号在其他地点登录', 'data' => []],200);
            return $next($request);
        } else {
            return json(['code' => 401, 'msg'  => '缺少ApiAuth', 'data' => []],200);
        }
    }
}